<?php

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

$is_formal = $_POST['custom'];

foreach ($_POST as $key => $value) {
  $value = urlencode(stripslashes($value));
  $req .= "&$key=$value";
}

// post back to PayPal system to validate
$header  = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";



// If testing on Sandbox use:
if ($is_formal == 0) {
  $server = 'www.sandbox.paypal.com';
} else {
  $server = 'www.paypal.com';
}

$fp = fsockopen ($server, 80, $errno, $errstr, 30);
  
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];

if (!$fp) {
  //HTTP ERROR
} else {
  fputs ($fp, $header . $req);
  while (!feof($fp)) {
    $res = fgets ($fp, 1024);
    if (strcmp ($res, "VERIFIED") == 0 || $is_formal == 0) {
      require_once dirname(__FILE__) . '/../../../DbUtils.class.php';
      require_once dirname(__FILE__) . '/../../../includes/MiscUtils.class.php';
      $myPdo = DbUtils::createPdoInst();
     
      $cond_vals = new stdClass();
      $cond_vals->c = 't.order_no = :v1';
      $cond_vals->v = array(':v1' => $item_name);
      $order = DbUtils::get(DbUtils::createPdoInst(), 'pz_ecom_order', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d[0];
      if ($order->is_paid == 0) {
	      $order->is_paid = 1;
	      DbUtils::update($myPdo, 'pz_ecom_order', $order);
	      
	      $total = 0;
	      $cond_vals = new stdClass();
	      $cond_vals->c = 't.order_id = :v1 AND t.customer_id = :v2';
	      $cond_vals->v = array(':v1' => $order->id, ':v2' => $order->customer_id);
	      $purchases = DbUtils::get(DbUtils::createPdoInst(), 'pz_ecom_purchase', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
	      if (count($purchases) > 0) {
          foreach ($purchases as &$purchase) {
            $cond_vals = new stdClass();
            $cond_vals->c = 'id = :v1';
            $cond_vals->v = array(':v1' => $purchase->product_id);
            $products = DbUtils::get(DbUtils::createPdoInst(), 'pz_ecom_product', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
            if (count($products) > 0) {
              $product = $products[0];
              if ($product->is_credit == 1) {
                $total += $purchase->total;
              }
              if ($product->stock_status == 1) {
                $product->stock = $product->stock - $purchase->quantity;
                DbUtils::update(DbUtils::createPdoInst(), 'pz_ecom_product', $product);
              }
            }
          }
        }
        
        $cond_vals = new stdClass();
        $cond_vals->c = 'id = :v1';
        $cond_vals->v = array(':v1' => $order->customer_id);
        $customers = DbUtils::get(DbUtils::createPdoInst(), 'pz_ecom_customer', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d;
        $points = DbUtils::get(DbUtils::createPdoInst(), 'pz_ecom_point', NULL, NULL, NULL, NULL, NULL, NULL)->d;
        if (count($customers) > 0) {
        	$customer = $customers[0];
	        if ($customer->customer_type != 'VIP会员') {
	        	if (count($points) > 0) {
		          $credit_points = $customer->credit_points + $total * $points[0]->rate;
		          if ($credit_points >= $points[0]->level2) {
		          	$customer->customer_type = '高级会员';
		          	$customer->credit_points = $credit_points;
		          } else if ($credit_points >= $points[0]->level1) {
		          	$customer->customer_type = '中级会员';
		          	$customer->credit_points = $credit_points;
		          } else {
		            $customer->customer_type = '普通会员';
	              $customer->credit_points = $credit_points;
		          }
		          DbUtils::update($myPdo, 'pz_ecom_customer', $customer);
	        	}
	        }
        }
      }
    } else if (strcmp ($res, "INVALID") == 0) {
      echo "The response from IPN was: <b>" .$res ."</b>";
    }
  }
  fclose ($fp);
}
?>